const balanceApi = require('../../api/balance.js')

Page({
  data: {
    loading: false,
    currentBalance: '0.00',
    
    // 充值金额选项
    amountOptions: [50, 100, 200, 500, 1000, 2000],
    selectedAmount: null,
    customAmount: '',
    finalAmount: 0,
    
    // 支付方式
    paymentMethods: [
      {
        code: 'WECHAT',
        name: '微信支付',
        desc: '使用微信钱包支付',
        icon: '💰'
      },
      {
        code: 'ALIPAY', 
        name: '支付宝',
        desc: '使用支付宝钱包支付',
        icon: '💳'
      },
      {
        code: 'SIMULATION',
        name: '模拟支付',
        desc: '仅供测试使用',
        icon: '🎯'
      }
    ],
    selectedPayment: 'SIMULATION',
    selectedPaymentName: '模拟支付',
    
    // 弹窗状态
    showPaymentModal: false,
    showResultModal: false,
    paying: false,
    
    // 支付结果
    paymentResult: {
      success: false,
      message: '',
      orderNo: ''
    }
  },

  onLoad(options) {
    if (!this.checkLoginStatus()) {
      return
    }
    
    this.loadCurrentBalance()
    // 如果传入了充值金额参数
    if (options.amount) {
      const amount = parseFloat(options.amount)
      if (amount > 0) {
        this.setData({
          customAmount: amount.toString(),
          finalAmount: amount
        })
      }
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const app = getApp()
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录后进行充值',
        showCancel: false,
        success: () => {
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
        }
      })
      return false
    }
    return true
  },

  onShow() {
    // 检查登录状态并刷新余额
    if (this.checkLoginStatus()) {
      this.loadCurrentBalance()
    }
  },

  // 加载当前余额
  async loadCurrentBalance() {
    try {
      const result = await balanceApi.getUserBalance()
      if (result.success) {
        this.setData({
          currentBalance: this.formatAmount(result.data.balance)
        })
      }
    } catch (error) {
      console.error('获取余额失败:', error)
    }
  },

  // 选择充值金额
  selectAmount(e) {
    const amount = e.currentTarget.dataset.amount
    this.setData({
      selectedAmount: amount,
      customAmount: '',
      finalAmount: amount
    })
  },

  // 自定义金额输入
  onCustomAmountInput(e) {
    const value = e.detail.value
    this.setData({
      customAmount: value,
      selectedAmount: null
    })
    
    // 实时计算最终金额
    const amount = parseFloat(value)
    if (!isNaN(amount) && amount > 0) {
      this.setData({
        finalAmount: amount
      })
    } else {
      this.setData({
        finalAmount: 0
      })
    }
  },

  // 自定义金额失焦处理
  onCustomAmountBlur(e) {
    const value = e.detail.value
    if (value) {
      const amount = parseFloat(value)
      if (!isNaN(amount) && amount > 0) {
        // 格式化显示
        this.setData({
          customAmount: amount.toFixed(2)
        })
      } else {
        wx.showToast({
          title: '请输入有效金额',
          icon: 'none'
        })
        this.setData({
          customAmount: '',
          finalAmount: 0
        })
      }
    }
  },

  // 选择支付方式
  selectPayment(e) {
    const code = e.currentTarget.dataset.code
    const method = this.data.paymentMethods.find(item => item.code === code)
    this.setData({
      selectedPayment: code,
      selectedPaymentName: method ? method.name : ''
    })
  },

  // 提交充值
  submitRecharge() {
    if (this.data.finalAmount <= 0) {
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none'
      })
      return
    }

    if (this.data.finalAmount < 1) {
      wx.showToast({
        title: '最低充值金额¥1.00',
        icon: 'none'
      })
      return
    }

    if (this.data.finalAmount > 50000) {
      wx.showToast({
        title: '单次充值不能超过¥50,000.00',
        icon: 'none'
      })
      return
    }

    if (!this.data.selectedPayment) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none'
      })
      return
    }

    // 显示支付确认弹窗
    this.setData({
      showPaymentModal: true
    })
  },

  // 关闭支付确认弹窗
  closePaymentModal() {
    this.setData({
      showPaymentModal: false
    })
  },

  // 确认支付
  async confirmPayment() {
    this.setData({ paying: true })

    try {
      // 模拟支付处理时间
      await this.simulatePayment()
      
      const rechargeData = {
        rechargeAmount: this.data.finalAmount,
        paymentMethod: this.data.selectedPayment,
        rechargeType: 'MANUAL',
        remark: `${this.data.selectedPaymentName}充值`
      }

      const result = await balanceApi.recharge(rechargeData)
      
      if (result.success) {
        // 充值成功
        this.setData({
          showPaymentModal: false,
          showResultModal: true,
          paymentResult: {
            success: true,
            message: '充值成功，余额已更新',
            orderNo: result.data || this.generateOrderNo()
          }
        })
        
        // 刷新余额
        this.loadCurrentBalance()
        
      } else {
        // 充值失败
        this.setData({
          showPaymentModal: false,
          showResultModal: true,
          paymentResult: {
            success: false,
            message: result.message || '充值失败，请重试',
            orderNo: ''
          }
        })
      }

    } catch (error) {
      console.error('充值失败:', error)
      this.setData({
        showPaymentModal: false,
        showResultModal: true,
        paymentResult: {
          success: false,
          message: error.message || '网络错误，请重试',
          orderNo: ''
        }
      })
    } finally {
      this.setData({ paying: false })
    }
  },

  // 模拟支付处理
  async simulatePayment() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟95%成功率
        const success = Math.random() > 0.05
        if (success) {
          resolve()
        } else {
          reject(new Error('模拟支付失败'))
        }
      }, 2000)
    })
  },

  // 生成订单号
  generateOrderNo() {
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    const time = now.getTime().toString().slice(-6)
    return `RC${year}${month}${day}${time}`
  },

  // 关闭结果弹窗
  closeResultModal() {
    this.setData({
      showResultModal: false
    })

    if (this.data.paymentResult.success) {
      // 充值成功，返回余额页面
      wx.navigateBack()
    } else {
      // 充值失败，重置表单
      this.resetForm()
    }
  },

  // 重置表单
  resetForm() {
    this.setData({
      selectedAmount: null,
      customAmount: '',
      finalAmount: 0,
      selectedPayment: 'SIMULATION',
      selectedPaymentName: '模拟支付'
    })
  },

  // 格式化金额
  formatAmount(amount) {
    if (!amount && amount !== 0) return '0.00'
    return parseFloat(amount).toFixed(2)
  },

  // 页面返回处理
  onUnload() {
    // 页面卸载时清理定时器等资源
  }
}) 